import request, { RequestOptionsInit } from 'umi-request'
import { message } from 'antd'
import { history } from 'umi'
import { stringify } from 'querystring'
import { getMachineId, getPageQuery, getStore, setStore, StoreKey } from './util'
import { config } from '@/config'

const codeMap = [9000]

request.interceptors.response.use(async (response, e) => {
    const data = await response.clone().json()
    if (codeMap.includes(data.flag)) {
        const { redirect } = getPageQuery()
        if (window.location.pathname !== '/login' && !redirect) {
            history.replace({
                pathname: '/login',
                search: stringify({
                    redirect: window.location.href,
                }),
            })
        }
    }
    if (data.flag === 9996) {
        if (window.location.pathname !== '/ver') {
            history.push('/ver')
        }
    }
    if (data.flag !== 1) {
        message.error(data.message)
    }
    return response
})

export const http = async ({
    url,
    method = 'POST',
    data,
    option,
}: {
    url: string
    method?: 'GET' | 'POST'
    data?: Record<string, any>
    option?: RequestOptionsInit
}) => {
    const Authorization = await getStore(StoreKey.TOKEN)
    return await request(url, {
        method,
        data,
        errorHandler: (err) => {
            console.error(err)
            message.error(err.message)
        },
        ...option,
        headers: { ...option?.headers, Authorization, devid: await getMachineId(), version: config.version },
    })
}
